//把配置项单独处理
import configs from '../config/wap.js'
import store from '@/store/index.js'; //vuex  

let server_url = configs.requestUrl; //请求地址
let token = ''; //凭证
// process.env.NODE_ENV === 'development' ? '192.168.0.1' : 'http://***/api' ; //环境配置
function service(options = {}) {
	token = uni.getStorageSync('tokens') ? uni.getStorageSync('tokens') : ''
	// store.state.token && (token = store.state.token); //从vuex中获取登录凭证
	options.url = `${server_url}${options.url}`;
	//配置请求头
	options.header = {
		identity: store.state.identity,
		['identity-staff-id']: store.state.identity_staff_id,
		// 'content-type': 'application/x-www-form-urlencoded',
		'tokens': `${token}` //Bearer 
	};
	options.method = options.method ? options.method : 'GET'
	// const loading_method = ['post', 'put', 'delete', 'POST', 'PUT', 'DELETE']
	// let boolLoading = loading_method.some(item => item == options.method)
	uni.showLoading({
		mask: true
	})
	return new Promise((resolved, rejected) => {
		//成功
		options.success = (res) => {
			if (Number(res.data.code) == 400) {
				//登录失效
				uni.setStorageSync('tokens', '')
				store.dispatch('clearState')
				uni.$showMsg(res.data.msg)
				// #ifdef H5
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/index'
					})
				}, 1000)
				// #endif
				// #ifdef MP-WEIXIN
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}, 1000)
				// #endif
			}
			resolved(res.data);
		}
		//错误
		options.fail = (err) => {
			rejected(err); //错误
		}
		options.complete = () => {
			uni.hideLoading()
		}
		uni.request(options);

	});
}
export default service;